package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constrant.ProductConst;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.product.entity.AttrEntity;
import com.atguigu.gulimall.product.entity.BrandEntity;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.entity.ProductAttrValueEntity;
import com.atguigu.gulimall.product.entity.SkuImagesEntity;
import com.atguigu.gulimall.product.entity.SkuInfoEntity;
import com.atguigu.gulimall.product.entity.SkuSaleAttrValueEntity;
import com.atguigu.gulimall.product.entity.SpuImagesEntity;
import com.atguigu.gulimall.product.entity.SpuInfoDescEntity;
import com.atguigu.gulimall.product.feign.CouponFeignService;
import com.atguigu.gulimall.product.feign.SearchFeignService;
import com.atguigu.gulimall.product.feign.WareFeignService;
import com.atguigu.gulimall.product.service.AttrService;
import com.atguigu.gulimall.product.service.BrandService;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.service.ProductAttrValueService;
import com.atguigu.gulimall.product.service.SkuImagesService;
import com.atguigu.gulimall.product.service.SkuInfoService;
import com.atguigu.gulimall.product.service.SkuSaleAttrValueService;
import com.atguigu.gulimall.product.service.SpuImagesService;
import com.atguigu.gulimall.product.service.SpuInfoDescService;
import com.atguigu.gulimall.product.vo.Attr;
import com.atguigu.gulimall.product.vo.BaseAttrs;
import com.atguigu.gulimall.product.vo.Bounds;
import com.atguigu.gulimall.product.vo.Images;
import com.atguigu.gulimall.product.vo.Skus;
import com.atguigu.gulimall.product.vo.SpuSaveVo;
import com.atguigu.to.SkuHasStockTo;
import com.atguigu.to.SkuReductionTo;
import com.atguigu.to.SpuBoundsTo;
import com.atguigu.to.es.SkuEsModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.SpuInfoDao;
import com.atguigu.gulimall.product.entity.SpuInfoEntity;
import com.atguigu.gulimall.product.service.SpuInfoService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

@Slf4j
@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private SpuImagesService spuImagesService;
    @Autowired
    private ProductAttrValueService productAttrValueService;
    @Autowired
    private SkuInfoService skuInfoService;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    private CouponFeignService couponFeignService;
    @Autowired
    private AttrService attrService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private WareFeignService wareFeignService;
    @Autowired
    private SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        //检索栏位
        String key = (String)params.get("key");
        if (StringUtils.isNotBlank(key)) {
            wrapper.and(cond ->cond.eq("id", key).or().like("spu_name", key));
        }
        //分类栏位
        String catelogId = (String)params.get("catelogId");
        if (StringUtils.isNotBlank(catelogId) && !StringUtils.equals(catelogId, "0")) {
            wrapper.eq("catalog_id", catelogId);
        }
        //品牌栏位
        String brandId = (String)params.get("brandId");
        if (StringUtils.isNotBlank(brandId) && !StringUtils.equals(brandId, "0")) {
            wrapper.eq("brand_id", brandId);
        }
        //状态栏位
        String status = (String)params.get("status");
        if (StringUtils.isNotBlank(status)) {
            wrapper.eq("status", status);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    /**
     * 此处实现涉及多张表保存和微服务调用所以添加事务
     * @param spuInfo
     */
    @Transactional
    @Override
    public void savaSpuInfo(SpuSaveVo spuInfo) {
        //1.spu基本信息 pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuInfo, spuInfoEntity);
        Date now = new Date();
        spuInfoEntity.setCreateTime(now);
        spuInfoEntity.setUpdateTime(now);
        this.baseMapper.insert(spuInfoEntity);

        Long spuId = spuInfoEntity.getId();

        //2.spu图片描述 pms_spu_info_desc
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuId);
        spuInfoDescEntity.setDecript(StringUtils.join(spuInfo.getDecript(), ","));
        this.spuInfoDescService.save(spuInfoDescEntity);

        //3.spu图片集 pms_spu_images
        List<String> images = spuInfo.getImages();
        if (!CollectionUtils.isEmpty(images)) {
            List<SpuImagesEntity> spuImageEntityList = images.stream().map(item -> {
                SpuImagesEntity spuImagesEntity = new SpuImagesEntity();
                spuImagesEntity.setSpuId(spuId);
                spuImagesEntity.setImgUrl(item);

                return spuImagesEntity;
            }).collect(Collectors.toList());
            this.spuImagesService.saveBatch(spuImageEntityList);
        }

        //4.spu基本属性（规格参数） pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuInfo.getBaseAttrs();
        if (!CollectionUtils.isEmpty(baseAttrs)) {
            List<ProductAttrValueEntity> productAttrValueEntityList = baseAttrs.stream().map(item -> {
                ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
                BeanUtils.copyProperties(item, productAttrValueEntity);
                productAttrValueEntity.setSpuId(spuId);
                Long attrId = item.getAttrId();
                productAttrValueEntity.setAttrId(attrId);
                AttrEntity attrEntity = attrService.getById(attrId);
                productAttrValueEntity.setAttrName(attrEntity.getAttrName());
                productAttrValueEntity.setAttrValue(item.getAttrValues());
                productAttrValueEntity.setQuickShow(item.getShowDesc());

                return productAttrValueEntity;
            }).collect(Collectors.toList());
            this.productAttrValueService.saveBatch(productAttrValueEntityList);
        }

        //5.会员积分信息 sms_spu_bounds   跨服务调用
        Bounds bounds = spuInfo.getBounds();
        SpuBoundsTo spuBoundsTo = new SpuBoundsTo();
        BeanUtils.copyProperties(bounds, spuBoundsTo);
        spuBoundsTo.setSpuId(spuId);
        R r1 = this.couponFeignService.saveSpuBoundsTo(spuBoundsTo);
        if (r1.getCode() != 0) {
            log.error("远程保存spu积分信息失败");
        }

        //6.spu的sku基本信息 pms_sku_info
        List<Skus> skus = spuInfo.getSkus();
        if (!CollectionUtils.isEmpty(skus)) {
            skus.forEach(item -> {
                //6.1sku基本信息
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                skuInfoEntity.setSpuId(spuId);
                BeanUtils.copyProperties(item, skuInfoEntity);
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setBrandId(spuInfo.getBrandId());
                skuInfoEntity.setCatalogId(spuInfo.getCatalogId());

                List<Images> imagesList = item.getImages();
                imagesList.stream().filter(k -> k.getDefaultImg() == 1)
                        .findFirst().ifPresent(img -> {
                    skuInfoEntity.setSkuDefaultImg(img.getImgUrl());
                });
                this.skuInfoService.save(skuInfoEntity);

                Long skuId = skuInfoEntity.getSkuId();

                //6.2sku图片信息 pms_sku_images
                List<SkuImagesEntity> skuImagesEntityList = imagesList.stream()
                        .filter(k -> StringUtils.isNotBlank(k.getImgUrl())).map(i -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    BeanUtils.copyProperties(i, skuImagesEntity);
                    skuImagesEntity.setSkuId(skuId);

                    return skuImagesEntity;
                }).collect(Collectors.toList());
                this.skuImagesService.saveBatch(skuImagesEntityList);

                //6.3sku销售属性 pms_sku_sale_attr_value
                List<Attr> attrList = item.getAttr();
                if (null != attrList && attrList.size() > 0 ) {
                    List<SkuSaleAttrValueEntity> skuSaleAttrValueEntityList = attrList.stream().map(attr -> {
                        SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                        BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                        skuSaleAttrValueEntity.setSkuId(skuId);

                        return skuSaleAttrValueEntity;
                    }).collect(Collectors.toList());
                    this.skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntityList);
                }

                //6.4sku的优惠满减信息 sms_sku_ladder sms_sku_full_reduction sms_member_price
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                skuReductionTo.setSkuId(skuId);
                BeanUtils.copyProperties(item, skuReductionTo);

                if (skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) == 1) {

                    R r2 = this.couponFeignService.saveSkuReduction(skuReductionTo);
                    if (r2.getCode() != 0) {
                        log.error("远程保存sku优惠信息失败");
                    }
                }

            });
        }
    }

    @Override
    public void spuInfoUp(Long spuId) {

        //4.sku的所有被检索的规格属性
        List<ProductAttrValueEntity> attrValueEntities = this.productAttrValueService.listForSpuInfo(spuId);
        List<Long> attrIds = attrValueEntities.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());
        List<AttrEntity> attrEntities = this.attrService.list(new QueryWrapper<AttrEntity>().in("attr_id", attrIds).eq("search_type", 1));
        List<Long> attrIdList = attrEntities.stream().map(AttrEntity::getAttrId).collect(Collectors.toList());
        List<SkuEsModel.Attrs> needAttrs = attrValueEntities.stream().filter(item -> attrIdList.contains(item.getAttrId()))
                .map(item -> {
                    SkuEsModel.Attrs attr = new SkuEsModel.Attrs();
                    BeanUtils.copyProperties(item, attr);
                    return attr;
                })
                .collect(Collectors.toList());

        //根据spuId查 所有sku信息
        List<SkuInfoEntity> skuInfoEntities = this.skuInfoService.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
        List<Long> skuIdList = skuInfoEntities.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        //远程调用，这里可能存在网络问题导致调佣失败，在这里记录日志
        Map<Long, Boolean> stockMap = null;
        try {

            R r = this.wareFeignService.hasStock(skuIdList);
            if (r.getCode() == 0) {
                stockMap = r.getData(new TypeReference<List<SkuHasStockTo>>(){}).stream().collect(Collectors.toMap(SkuHasStockTo::getSkuId, SkuHasStockTo::getHasStock));
            }
        } catch (Exception e) {
            log.error("库存服务查询异常：原因【{}】;查询的skuIds【{}】", e, skuIdList);
        }

        Map<Long, Boolean> finalStockMap = stockMap;
        List<SkuEsModel> skuEsModels = skuInfoEntities.stream().map(item -> {
            SkuEsModel skuEsModel = new SkuEsModel();
            //同名属性直接拷贝
            BeanUtils.copyProperties(item, skuEsModel);
            //不同名属性设置
            skuEsModel.setSkuPrice(item.getPrice());
            skuEsModel.setSkuImg(item.getSkuDefaultImg());

            //1. 远程查库存系统，看是否有库存
            skuEsModel.setHasStock(finalStockMap.get(item.getSkuId()));

            //2.热度评分，简化处理 给0；实际场景应该是后台可控的复杂操作
            skuEsModel.setHotScore(0L);

            //3.品牌名 品牌默认图片 分类名
            BrandEntity brandEntity = this.brandService.getById(item.getBrandId());
            if (null != brandEntity) {
                skuEsModel.setBrandName(brandEntity.getName());
                skuEsModel.setBrandImg(brandEntity.getLogo());
            }
            CategoryEntity categoryEntity = this.categoryService.getById(item.getCatalogId());
            if (null != categoryEntity) {
                skuEsModel.setCatalogName(categoryEntity.getName());
            }

            //4.sku的所有被检索的规格属性
            skuEsModel.setAttrs(needAttrs);
            return skuEsModel;
        }).collect(Collectors.toList());

        // 5.保存数据到es
        R up = this.searchFeignService.productUp(skuEsModels);
        if (up.getCode() == 0) {
            //远程调佣es存储数据成功
            //6.更新商品的状态
            this.baseMapper.updateProductStatus(spuId, ProductConst.StateEnum.UP_SPU.getCode());
        } else {
            //远程调用失败
            //7.重复调用 接口幂等性 重试机制 todo
        }
    }
}